package com.kedacom.general.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kedacom.general.param.RequestParam;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

public class RequestBodyUtil {
    // 获取请求参数体
    public static RequestParam getRequestParam(HttpServletRequest request) throws IOException {
        RequestParam requestParam = new RequestParam();
        JSONObject jsonObject = new JSONObject();
        String str, wholeStr = "";
        try {
            if (StringUtils.isEmpty(request.getContentType()) || !request.getContentType().contains("multipart/form-data")) {
                BufferedReader br = request.getReader();

                while ((str = br.readLine()) != null) {
                    wholeStr += str;
                }
                if (!StringUtils.isEmpty(wholeStr)) {
                    wholeStr=wholeStr.trim();
                    //判断参数方式是json还是url方式
                    if(wholeStr.startsWith("{"))
                    {
                        jsonObject= JSON.parseObject(wholeStr);
                    }
                    else {
                        for (String str1 : wholeStr.split("&")) {
                            jsonObject.put(str1.split("=")[0], str1.split("=")[1]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            //使用json方式解析

        }
        Enumeration names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getParameter(name);
            jsonObject.put(name, value);
        }
        requestParam.setParam(jsonObject);
        return requestParam;
    }
}
